/* Copyright Andy Mitchell 2007. No warranties */

function Lightbox(gtdinboxPage, elParent, type){
	this._gtdinboxPage = gtdinboxPage;
	this._doc = gtdinboxPage.doc;
	this._labels = gtdinboxPage._labels;
	this._eventObservers = new EventObservers(this);
	this._eventHandlers = new EventHandlers_Mutator(this);
	this._xmlHttpRequest = new GIXMLHttpRequest(gtdinboxPage);
	
	this._create(elParent);
	this.setType(type);
};


Lightbox.prototype._create = function(elParent){
	this.el = this._doc.createElement("DIV");
		this.el.className = "lightbox";
		this.el.setAttribute("style", "display:none;");
	if( elParent ) elParent.appendChild( this.el );
	
	this.elContainer = this._doc.createElement("DIV");
		this.elContainer.className = "lightbox-container";
		this.elContainer.setAttribute("style", "margin:auto;z-index:5001;width:800px;");
	this.el.appendChild( this.elContainer );
};

Lightbox.prototype.setType = function(type, options){
try{
	this._type = type;
		
	var el = this._doc.createElement("DIV");
	if( type=="welcome" ){
		var msg = GTDFileIO.readFromUrl( this._gtdinboxPage.gtdinboxBrowser.getLocalHtmFile("welcome") );
		var match = msg.match(/<body[^>]*>((.|\r|\n|\t|\e|\f|\a|\v)+)<\/body>/i);
		el.innerHTML = match[1];
		this.content(el);
		
		this._createBasicLabels();
				
		var elProceed = this._doc.getElementById("gtd-welcome-proceed");
		this._eventObservers.observe(elProceed, "mousedown", this._welcomeProceed, false);
		
		this._createBasicLabels();
	}else if( type=="update" ){
		var msg = GTDFileIO.readFromUrl( this._gtdinboxPage.gtdinboxBrowser.getLocalHtmFile("update") );
		var match = msg.match(/<body[^>]*>((.|\r|\n|\t|\e|\f|\a|\v)+)<\/body>/i);
		el.innerHTML = match[1];
		//var apply = GIPROTOTYPE.bind(this, function(){
			this.content(el);
			
			var elProceed = this._doc.getElementById("gtd-update-gettingstarted");
			this._eventObservers.observe(elProceed, "mousedown", this._updateProceed, false);
			
			this._retainOldPrefixes();	// keep any old labels if labels found, otherwise use latest
			this._createBasicLabels();	// for any that don't exist - if deleted since last installed
		//});
		//setTimeout(apply, 200);
	}else if( type=="options" ){
		var msg = GTDFileIO.readFromUrl( this._gtdinboxPage.gtdinboxBrowser.getLocalHtmFile("options") );
		var match = msg.match(/<body[^>]*>((.|\r|\n|\t|\e|\f|\a|\v)+)<\/body>/i);
		el.innerHTML = match[1];
		this.content(el);
			
		this._options = new Options(this._gtdinboxPage, el, this, options);
	}else if( type=="gettingstarted" ){
		var msg = GTDFileIO.readFromUrl( this._gtdinboxPage.gtdinboxBrowser.getLocalHtmFile("gettingstarted") );
		var match = msg.match(/<body[^>]*>((.|\r|\n|\t|\e|\f|\a|\v)+)<\/body>/i);
		el.innerHTML = match[1];
		this.content(el);
		
		var elMigrateContainer = this._doc.getElementById("gtd-update-migrate-container");
		var elMigrate = this._doc.getElementById("gtd-update-migrate");
		this._gtdinboxPage.unsafeWindow.console.log("gettingstarted:");
		this._gtdinboxPage.unsafeWindow.console.log(elMigrate);
		this._eventObservers.observe(elMigrate, "mousedown", this._updateMigrate, false);
		
		
		var elClose = this._doc.getElementById("gtd-gettingstarted-proceed");
		this._eventObservers.observe(elClose, "mousedown", GIPROTOTYPE.bind(this, function(event){
				this.active(false);
			}), false);

		if( options && options.updating ){
			elMigrateContainer.style.display = "";
			elClose.style.display = "none";
		}
		
	}else if( type=="debug" ){
		var html = [];
		html.push("<div class='gtdmsg'>");
		html.push("<button id='gtdinbox.debug.close'>Close</button>");
		html.push("GTDInbox: Different Gmails Debugger");
		html.push("View: <span id='gtdinbox.debug.view.tl'>Thread List</span>, <span id='gtdinbox.debug.view.cv'>Conversation</span>, <span id='gtdinbox.debug.view.co'>Compose</span>, <span id='gtdinbox.debug.view.ct'>Contacts</span>");
		html.push("");
		html.push("There are many oh-so-slightly different variants of Gmail running in the world, which can de-stabalise GTDInbox (as it's developed on just my machine, and therefore just my Gmail)");
		html.push("The reason being I suspect Gmail does constant rolling global deployment, one server at a time, meaning users on different servers see slightly different things");
		html.push("(For the record, it seems language plays a role... i.e. English US get updates before almost anyone else)");
		html.push("");
		html.push("What symptoms will you get? Well, GTDInbox may appear to glitch, in a way that can be attributed to it failing to find part of the page.");
		html.push("");
		html.push("What is this? As I cannot actually play with your version of Gmail to diagnose the problem, I have to hope enough tech-savvy users experience the differences and are able to tell me what's failing and how to fix it.");
		html.push("To help with this, this Debug window trys to find all the common GTDInbox-related elements, using a custom XPath directive, and tells you when it fails (or more subtly, when the inner HTML - aka text - is not as expected).");
		html.push("If you want to dig in, load up the source (search for GmailDOM.js on your machine - it has code for all the element keys), and load at the XPath statement. This is what will most likely fail. If you use Firebug - and enable it in Gmail - you can then follow the failed XPath and try to work out your own XPath that will work on your Gmail. If you then send that to me, I can incorporate it into the general release; the fixing the issue for everyone");
		html.push("");
		html.push("<table><tbody id='gtdinbox.debug'><tr><td width='30%'>Element Key in GmailDOM.js</td><td width='10%'>Found</td><td width='60%'>Found Inner HTML</td></tr></tbody></table>");
		html.push("</div>");
		
		el.innerHTML = html.join("<br/>");
		this.content(el);
		
		var doc = this.elContent.ownerDocument;
		
		var view = this._gtdinboxPage.view();
		var elView = doc.getElementById("gtdinbox.debug.view." + view);
		if( elView ) elView.style.fontWeight = "bold";
		
		var elClose = doc.getElementById("gtdinbox.debug.close");
		this._eventObservers.observe(elClose, "mousedown", GIPROTOTYPE.bind(this, function(event){
				this.active(false);
			}), false);
				
		var elTBody = doc.getElementById("gtdinbox.debug");
		var renderElement = GIPROTOTYPE.bind(this, function(key, notes){
			var el = this._gtdinboxPage.gmailDOM.element(key);
			var elTr = this._doc.createElement("TR");
				elTr.setAttribute("valign","top");
			var elTd = this._doc.createElement("TD");
				elTd.innerHTML = key;
				elTd.setAttribute("valign","top");
			elTr.appendChild(elTd);
			var elTd = this._doc.createElement("TD");
				elTd.innerHTML = !!(el);
			elTr.appendChild(elTd);
			var elTd = this._doc.createElement("TD");
				if( el ) elTd.innerHTML = GIPROTOTYPE.decodeEntities(el.innerHTML.replace(/<[^>]+>/g, ""));
				if( el && el.value ) elTd.innerHTML += "<br/>(Value: " + el.value + ")";
				if( notes ) elTd.innerHTML += "<br/><i>[" + notes + "]</i>";
			elTr.appendChild(elTd);
			
			elTBody.appendChild(elTr);
		});
		
		renderElement("action-combo");
		renderElement("action-combo-list", "May be false. That's ok.");
		renderElement("email-address");
		renderElement("alert-box", "No inner HTML");
		renderElement("search-box", "No inner HTML");
		renderElement("search-button");
		renderElement("search-row");
		renderElement("nav-buckets");
		renderElement("inbox-link");
		renderElement("compose-mail");
		
		if( view=="tl" ){
			renderElement("archive-button");
			renderElement("spam-button");
			renderElement("delete-button");
			renderElement("threadlist-refresh");
		}
		
		if( view=="cv" ){
			renderElement("conversation-header");
			renderElement("conversation-subject");
		}
		
		if( view=="co" ){
			renderElement("plain-textarea", "No inner HTML");
			renderElement("compose-to", "No inner HTML");
			renderElement("compose-table" );
		}
		
		if( view=="ct" ){
			renderElement("contacts-frame-body");
		}
		
	};
	
}catch(e){
	if( GTDDEBUGMODE ) alert("Lightbox setType\n" + e.toString());
	this.active(false);
}
};

Lightbox.prototype._welcomeProceed = function(event){
	// Just show Gmail
	this.setType("gettingstarted");
};
Lightbox.prototype._updateMigrate = function(event){
	// Load the options, with defaults included
	// Update the current labels to be 1.33 (or if not relevant, latest); and restore any missing defaults. Then move to migrate to latest.
try{
	var settings = this._gtdinboxPage.createDefaultSettings();
	var newTypes = settings.labels.types;		
	this.setType("options", {prefixNewTypes:newTypes});
}catch(e){
	if( GTDDEBUGMODE ) alert( "Lightbox _updateMigrate\n" + e.toString());
}
};
Lightbox.prototype._updateProceed = function(event){
	this.setType("gettingstarted", {updating:true});
};


Lightbox.prototype._retainOldPrefixes = function(){
	// For each prefix, if any instance (label) with old prefix; keep that old prefix. If not, use new prefix.
	
	var labels = this._labels.getLabelsArray();
	var settings = this._gtdinboxPage.settings;
	var options = this._gtdinboxPage.gtdinboxBrowser.options;
	for( l in settings.labels.types ){
		var oldKey = l.replace(/s$/, "");
		if( /se$/.test(oldKey) ) oldKey = oldKey.replace(/e$/, "");
		var oldPrefix = options.getOption("char", "GTDInbox_Prefix_" + oldKey );
		var found = false;
		for( var i = 0; i < labels.length; i++ ){
			if( labels[i].indexOf(oldPrefix)==0 ){	// Old Prefix matches, retain it
				found = true;
				break;
			}
		}
		if( found ){
			this._gtdinboxPage.settings.labels.types[l].prefix = oldPrefix;
		}else{
		}
	}
	this._gtdinboxPage.saveSettings();
};
Lightbox.prototype._createBasicLabels = function(callback){
try{
	// Using the current prefix (set correctly elsewhere); see if any labels are missing. If so, add them.
		
	var at = this._gtdinboxPage.gmailDOM.local("at");
	if( !callback && !at ){
		setTimeout( GIPROTOTYPE.bind(this, function(){this._createBasicLabels(true)}), 2000);	// need correct environment variables to load before can ajax call gmail
	}
		
	var labelsHash = this._labels.getLabelsHash();
	
	var settings = this._gtdinboxPage.settings;
	//settings.labels.types["Statuses"]
	
	var labels = [];
	for( t in settings.labels.types ){
		if( settings.labels.types[t].defaults ){
			var prefix = settings.labels.types[t].prefix;
			for( d in settings.labels.types[t].defaults ){
				var label = prefix + settings.labels.types[t].defaults[d];
				if( !labelsHash[label] ) labels.push(label);
			}
		}
	}
	
	
	
	var finalCallback = GIPROTOTYPE.bind(this, function(){
				var el = this._gtdinboxPage.gmailDOM.element("inbox-link");
				GIPROTOTYPE.doMouseEvent(this._doc, el, "click");	// refresh
			});
	if( labels.length>0 ) var at = this._gtdinboxPage.gmailDOM.addLabel(labels, null, finalCallback);
	
	/*
	var count = {i:0};
	// Add all of labels now
	for( var i = 0; i < labels.length; i++ ){
		var request = {};
		request.url = "http://mail.google.com/mail/?ui=2";
		request.url += "&ik=" + ik
		request.url += "&at=" + at;
		request.url += "&view=up&act=cc_" + encodeURI(labels[i]) + "&rt=h";
		request.callback = GIPROTOTYPE.bind(this, function(){
				if( --count.i==0 ){
					var el = this._gtdinboxPage.gmailDOM.element("inbox-link");
					GIPROTOTYPE.doMouseEvent(this._doc, el, "click");	// refresh
				}
			});
		count.i++;
		this._xmlHttpRequest.process(request);
	}
	*/
}catch(e){
	if( GTDDEBUGMODE ) alert("lightbox createbasiclabels\n" + e.toString());
}
};



Lightbox.prototype.active = function(v){
	if( typeof v=="undefined" ) return this.el.style.display!="none";
	if( v ){
		this._eventHandlers.broadcast("beforeactivate");
		this.el.style.display = "";
		this._eventObservers.observe(window, "resize", this._position, false );
		this._eventHandlers.broadcast("activated");
		this._position();
		
	}else{
		this.el.style.display = "none";
		this._eventObservers.stopObserving(window, "resize", this._position, false );
		this._eventHandlers.broadcast("deactivate");
		this.lastDims = null;
	}
		
};

Lightbox.prototype.content = function(el){
try{
	if( typeof el=="undefined" ) return this.elContent;
	
	while( this.elContainer.firstChild ) this.elContainer.removeChild( this.elContainer.firstChild );
	
	
	
	this.elContent = el;
	this.elContainer.appendChild( el );
	
	this._position();
}catch(e){
	if( GTDDEBUGMODE ) alert("Lightbox content\n" + e.toString());
}
};
Lightbox.prototype._position = function(){
	// Correctly position container, based on its content's dimensions

	var winDims = GIPROTOTYPE.viewport(this._doc, this._gtdinboxPage.window);
	var cDims = GIPROTOTYPE.getDimensions(this.elContainer, this._doc);
				
	this.el.style.height = winDims[1] + "px";
	this.el.style.width = winDims[0] + "px";
	
	
};


Lightbox.prototype.destroy = function(){
	this._eventObservers.destroy();
	this._eventHandlers.destroy();
	
	this._xmlHttpRequest = null;
	this._gtdinboxPage = null;
	this._doc = null;
	this._labels = null;
	
	this.el = null;
	this.elContainer = null;
};